<template>
  <Overlay :show="mixIsShow" :persistent="persistent" @click-overlay="clickOverlay">
    <transition :name="'out-' + direction" @after-leave="afterLeave">
      <div
        v-show="mixIsShow"
        ref="popup"
        class="popup"
        :class="['popup-' + direction]"
        :style="popupComputedStyle"
      >
        <slot />
      </div>
    </transition>
  </Overlay>
</template>
<script>
import Overlay from '../overlay'
import mixShow from '@/mixins/show'
export default {
  name: 'Popup',
  components: {
    Overlay
  },
  mixins: [mixShow()],
  props: {
    persistent: {
      type: Boolean,
      default: false
    },
    direction: { // 方位
      type: String,
      default: 'bottom',
      validator (val) {
        return ['right', 'bottom'].includes(val)
      }
    },
    popupStyle: {
      type: Object,
      default: () => ({})
    },
    popupHeight: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      afterLeaveed: true
    }
  },
  computed: {
    // popup弹层的高度
    popupComputedStyle () {
      return Object.assign(
        this.popupStyle,
        this.popupHeight ? { height: this.popupHeight } : {}
      )
    }
  },
  watch: {
    mixIsShow (val) {
      val && this.afterLeaveed && (this.afterLeaveed = false)
      // 自定义高度时，计算容器高度
      if (this.mixIsShow && this.popupHeight) {
        this.$nextTick(() => {
          const refs = this.$refs
          refs.popupCon.style.height = (refs.popup.clientHeight - refs.popupTitle.clientHeight) + 'px'
        })
      }
      // 阻止滚动穿透  真机touchmove.prevent不生效
      if (this.mixIsShow) {
        document.body.style.overflow = 'hidden'
      } else {
        document.body.style.overflow = 'auto'
      }
    }
  },
  methods: {
    afterLeave () {
      this.afterLeaveed = true
    },
    clickOverlay () {
      this.mixIsShow = false
      this.$emit('click-overlay')
    }
  }
}
</script>

<style lang="less" scoped>
.popup {
  display: block;
  z-index: 2;
  background: #ffffff;
  position: fixed;
  overflow: auto;
}
.popup-right {
  height: 100%;
  right: 0;
  top: 0;
  max-width: 75vw;
}
.popup-bottom {
  bottom: 0;
  left: 0;
  width: 100%;
  border-radius: 8px 8px 0 0;
  max-height: 77vh;
  display: flex;
  flex-direction: column;
}

.out-right-enter-active,
.out-right-leave-active,
.out-bottom-enter-active,
.out-bottom-leave-active {
  transition: transform .3s;
}
.out-right-enter,
.out-right-leave-to {
  transform: translate3d(100%, 0, 0);
}

.out-bottom-enter,
.out-bottom-leave-to {
  transform: translate3d(0, 100%, 0);
}
</style>
